package com.gowants.pems.service;

import com.gowants.pems.mapper.EquipmentMaintainMapper;
import com.gowants.pems.mapper.EquipmentMapper;
import com.gowants.pems.model.Equipment;
import com.gowants.pems.model.EquipmentMaintain;
import com.gowants.pems.model.SysDict;
import com.gowants.pems.util.DateUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class EquipmentMaintainService {

    @Autowired
    private EquipmentMaintainMapper mapper;
    @Autowired
    private EquipmentMapper eMapper;
    @Autowired
    private SysDictService sysDictService;

    /**
     * 修改保养记录
     * @param record
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int  editEquipmentMaintain(EquipmentMaintain record) {
        int i=0;
        i=mapper.update(record);
        if(i>0) {
        	EquipmentMaintain record1=mapper.selectOne(record.getId());
        	EquipmentMaintain record0=new EquipmentMaintain();
	        Equipment equipment=eMapper.selectById(record1.getEquipmentId());
	        if(1!=equipment.getCycle()) {
		        SysDict dict = new SysDict();
				dict.setDictId(equipment.getCycle());
				dict.setGroupId("equipment_cycle");
				List<SysDict> sysDict = sysDictService.selectList(dict);
				String unit[] = null;
				if (sysDict.size() > 0) {
					unit = sysDict.get(0).getRemarks().split(",");
				}
				
				Date date = record.getOperationTime(); // 第一次执行定时任务的时间
				date = this.addDay(date, Integer.parseInt(unit[0]), Integer.parseInt(unit[1]));
				record0.setId(UUID.randomUUID().toString());
				record0.setEquipmentId(equipment.getId());
				record0.setState(0);
				record0.setCreateTime(DateUtil.getDate());
				record0.setEndTime(date);
		        mapper.insert(record0);
	        }
        }
        return i;
    }
    
	// 增加或减少天数
	public Date addDay(Date date, int num, int type) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		switch (type) {
		case 1:
			break;
		case 2:
			startDT.add(Calendar.DATE, num);
			break;
		case 3:
			startDT.add(Calendar.MONTH, num);
			break;
		case 4:
			startDT.add(Calendar.YEAR, num);
			break;
		}
		return startDT.getTime();
	}
}
